import { Message } from "@arco-design/web-vue";
import axios from "axios";
import { createApp } from 'vue'
import Loading from '../src/components/Loading.vue';
let loadingInstance = null;
let loadingContainer = null;
let loadingCount = 0;
//此处对axios进行封装。
const targetUrl = import.meta.env.VITE_APP_API_URL
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8' //配置请求头
const service = axios.create({
  baseURL: targetUrl,
  timeout: 10000, //10秒超时
});

//设置请求拦截器
service.interceptors.request.use((config) => {
  showLoading();
  config.headers['Authorization'] = localStorage.getItem("Authorization");
  config.headers['accept-language'] = localStorage.getItem("lang") || 'zh_CN';
  return config;
})
//设置响应拦截器
service.interceptors.response.use(
  (response) => {
    hideLoading();
    let res;
    if (response.data === null) {
      res = response;
    } else {
      res = response.data;
    }
    // 如果结果正常 则正常放行
    if (res.code == 200) {
      if (res.msg === "登录成功") { Message.success('登陆成功！') }
      return res;
    }
    else {
      // this.$message.error(res.msg)
      Message.error(res.msg);
      return res;
    }
  },
  (error) => {
    Message.error(`请求错误，请稍后重试或重新登陆：${error.message}`);
    hideLoading();
    // 如果报错（status ！== 200）
    console.error('请求错误:', error.response ? error.response.data : error.message);
    return Promise.reject(error); // 使请求链继续，reject 错误

  }
);

export const request = ({
  url,
  method,
  data
}) => {
  method = method.toUpperCase(); // 统一转为大写
  
  if (method === "GET") {
    // 拼接get请求
    if (data) {
      url += "?" + splicingParams(data);
    }
    return service.get(url);
  } else if (method === "POST") {
    return service.post(url, data);
  } else if (method === "DELETE") { // 新增DELETE方法处理
    // 处理两种DELETE请求方式：
    // 1. 带body的DELETE请求：return service.delete(url, { data })
    // 2. 参数在URL的DELETE请求：return service.delete(url, { params: data })
    return service.delete(url, { params: data }); // 根据后端接口需求选择
  } else {
    console.error("未知方法：" + method);
    return Promise.reject(new Error(`未知方法：${method}`)); // 添加错误返回
  }
}

//拼接url
const splicingParams = (params) => {
  const searchParams = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    if(value === null || value === undefined || value === "") continue;
    searchParams.append(key, value);
  }
  return searchParams.toString();
};

//展示loading
function showLoading() {
  loadingCount++;
  if (loadingCount === 1) {
    loadingContainer = document.createElement('div');
    loadingContainer.id = 'loading-container';
    document.body.appendChild(loadingContainer);
    loadingInstance = createApp(Loading);
    loadingInstance.mount(loadingContainer);
  }
}
function hideLoading() {
  loadingCount--;
  if (loadingCount === 0) {
    const div = document.getElementById('loading-container');
    if (!div) {
      return;
    }
    document.body.removeChild(div);
    loadingInstance.unmount();
    loadingInstance = null;
    loadingContainer = null;
  }
}
export default request;